<?php

class ArticleController extends FController
{
	public $layout='//layouts/main';   
	/* 
		Function init can not set default theme for this controller
		It must be set in earch action
	*/ 
	
	public function init()
	{
		
		Yii::app()->theme = 'frontend';
		parent::init();
	}


	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionRevision($id = null)
	{
		$model = Article::model()->findByPk($id);
		
		
		$criteria=new CDbCriteria;
		$criteria->compare('is_published', 1, true);
		$criteria->compare('p_id', $model->id, true);
		$criteria->order = "created DESC";
	
		$dataProvider=new CActiveDataProvider('RevisionArticle', array(
			'criteria'=>$criteria,
			'pagination'=>array(
				'pageSize'=> 10,
				'pageVar'=>'page',
			),
		));
		
			$this->render('index',array(
				'model'=>$model,
				'dataProvider'=>$dataProvider,
			));
	}
	public function actionDelete($id = null  , $pid = null){
		$modelNew = RevisionArticle::model()->findByPk($id)->delete();
		$this->redirect(Yii::app()->createUrl('/articles/update',array('id'=>$pid)));
	}
	public function actionRevert($id = null , $pid = null)
	{
		$model = Article::model()->findByPk($pid);
		$modelNew = RevisionArticle::model()->findByPk($id);
		
		$revision = new RevisionArticle;
		$revision->attributes = $model->attributes;
		$revision->p_id = $model->id;
		$revision->user_id = $model->user_id;
		$revision->alias = $model->alias;
		$revision->title = $model->title;
		$revision->description = $model->description;
		$revision->content = $model->content;
		$revision->priority = $model->priority;
		$revision->country_id = $model->country_id;
		$revision->category_id = $model->category_id;
		$revision->verified_count = $model->verified_count;
		$revision->is_published = $model->is_published;
		$revision->source = $model->source;
		$revision->created = date("Y-m-d G:i:s");
		$revision->modified = date("Y-m-d G:i:s");
		
		if($revision->save()){
			
		}else{
			$errors  = $revision->getErrors();
			list ($field, $_errors) = each ($errors);
			Yii::app()->user->setFlash('error', 'Article revert failer.'.$_errors[0]);
			$this->redirect(array('update', 'id' => $model->id));
		}
		
		$model->attributes = $modelNew->attributes;
		
		
		 
		
		if ($model->save()) {
			Yii::app()->user->setFlash('success', 'Revert article successfully.');
			$this->redirect(Yii::app()->createUrl('/articles/update',array('id'=>$model->id)));
		}
		
		// dump($model->title,false);
		// dump($modelNew->title,false);
		// dump($id,false);
		// dump($pid);
	}
		
}
